package ar.edu.itba.it.pdc.httpParser.models;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import ar.edu.itba.it.pdc.nio.ByteBufferPool;
import ar.edu.itba.it.pdc.nio.MemoryAllocationLimitHited;

public class HttpHeader {
	
	private List<Token> headerName;
	private List<Token> headerValue;
	
	ByteBuffer byteBuffer;

	public HttpHeader(List<Token> headerName, List<Token> headerValue) {
		this.headerName = headerName;
		this.headerValue = headerValue;
	}

	public HttpHeader(String name, String value) {
		headerName = new LinkedList<Token>();
		headerValue = new LinkedList<Token>();
		headerName.add(new Token(name));
		headerValue.add(new Token(value));
	}

	public String getValue() {
		String str = "";
		for (Token token : headerValue) {
			str += token.toString();
		}
		return str;
	}
	
	public String getName() {
		String str = "";
		for (Token token : headerName) {
			str += token.toString();
		}
		return str;
	}
	
	public void add(List<Token> aggregatedValue) {
		headerValue.addAll(aggregatedValue);
	}
	

	private void add(Queue<ByteBuffer> queue, char c) throws MemoryAllocationLimitHited {
		byteBuffer.put((byte) c);
		if (byteBuffer.remaining() == 0) {
			byteBuffer.flip();
			queue.add(byteBuffer);
			byteBuffer  = ByteBufferPool.getInstance().getByteBuffer();
		}
	}

	public void appendByteBuffers(Queue<ByteBuffer> queue) throws MemoryAllocationLimitHited {
		if(byteBuffer == null)
			byteBuffer = ByteBufferPool.getInstance().getByteBuffer();

		for (Token token : headerName) {
			for (byte b : token.getName()) {
				add(queue, (char) b);
			}
		}

		add(queue, ':');

		for (Token token : headerValue) {
			if (!token.is(",")) {
				for (Byte c : token.getName()) {
					add(queue, (char) c.byteValue());
				}
			}
		}

		add(queue, '\r');
		add(queue, '\n');

		if (byteBuffer.position() != 0) {
			byteBuffer.flip();
			queue.add(byteBuffer);
			byteBuffer = null;
		}
	}

}
